<?php
namespace User\Controller;
use Think\Controller;
use Think\Log;

/**
 * @Author: Martin Zhou
 * @Version: 1.0.1
 * @Copyright Tencent Security Response Center (TSRC)
 * @Project  https://security.tencent.com/index.php/xsrc
*/

class ForgetController extends Controller {
    //显示找回密码页面
    public function index(){
        $this->display();
    }
	//验证码
    public function verify(){
		ob_clean();
        $Verify = new \Think\Verify();
        $Verify->codeSet = '123456789abcdefghijklmnopqrst';
        $Verify->fontSize = 20;
        $Verify->length = 4;
        $Verify->entry();
    }
    protected function check_verify($code, $tab){
        $verify = new \Think\Verify();
        return $verify->check($code,$tab);
    }
    //找回密码逻辑
    public function find(){
        if(!IS_POST)$this->error("非法请求");
        $rawData = file_get_contents("php://input");
        // 解码 JSON 数据
        $data = json_decode($rawData, true); // 第二个参数为 true 返回数组，若为 false 则返回对象 
        $code = $data['verify'];
        $email =  $data['email'];
        $username =  $data['username'];
        $member = M('member'); 
        //验证验证码是否正确
        if(!($this->check_verify($code,'forgetPwd'))){
            //$this->error('验证码错误');
            $result = ['code'=> 400, 'msg' => '验证码错误'];
            $this->ajaxReturn($result,'JSON'); 
        }
        //验证输入邮箱是否存在
        $user = $member->where(array('username'=>$username,'email'=>$email))->find();
		$salt = $member->where(array('email'=>$email,'username'=>$username))->find();
		
        if(!$user) {
            //$this->error('邮箱不存在 :(') ;
            $result = ['code'=> 400, 'msg' => '邮箱不存在'];
            $this->ajaxReturn($result,'JSON'); 
        }
        //验证账户是否被禁用
        if($user['status'] == 0){
            //$this->error('账号被禁用，无法找回密码 :(') ;
            $result = ['code'=> 400, 'msg' => '账号被禁用，无法找回密码'];
            $this->ajaxReturn($result,'JSON'); 
        }
         
		if($user['type'] == 2){
            //$this->error('前台无法重置管理员密码 :(') ;
            $result = ['code'=> 400, 'msg' => '前台无法重置管理员密码'];
            $this->ajaxReturn($result,'JSON'); 
        }
		
		//发送验证码邮件
        $str = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		mt_srand();
        $passwd=$str[mt_rand(0,61)].$str[mt_rand(0,61)].$str[mt_rand(0,61)].$str[mt_rand(0,61)].$str[mt_rand(0,61)].$str[mt_rand(0,61)].$str[mt_rand(0,61)].$str[mt_rand(0,61)].$str[mt_rand(0,61)].$str[mt_rand(0,61)];
        $content = md5(md5(md5($salt['salt']).md5($passwd)."SR")."CMS");
		$member = M('member');
		$member-> password=$content;
		$member ->where(array('username'=>$username,'email'=>$email))->save();
		$html='尊敬的'.$username.':<br/>您正在找回密码，您的临时新密码为 <b>'.$passwd.'</b> 请妥善保管，登陆平台后请及时修改密码。';  
//         if(SendMail($email,'找回密码',$con,'应急响应中心')){
// 			$this->success("发送成功",U('login/index'));
//         }else{  
// 			$this->error('密码找回邮件发送失败，请重试 :(') ;
//         }  
        $subject = "找回密码";
        //发送邮件
        $data['email'] = $email;
        $config = self::email_config();
        $send_email = $config['mail_from'];
        $msg = date('Y-m-d H:i:s', time()).":开始 $send_email 发送邮件到 $email\r\n";
        Log::record($msg);
        $obj = new \Extend\Email($config);
        $result = $obj->to($email)->subject($subject)->message($html)->send();
        if($result){
            $result = ['code'=> 200, 'msg' => '发送成功', 'url' => U('login/index')];
            $this->ajaxReturn($result,'JSON'); 
        }else{
            $result = ['code'=> 400, 'msg' => '密码找回邮件发送失败，请重试 '];
            $this->ajaxReturn($result,'JSON'); 
        }
    }
    
    
    /**
     * 邮件配置
     * @return string[]|mixed
     */
    public static function email_config(){
        $site_mail_smtp_user = M('setting')-> where(array('name'=>'site_mail_smtp_user')) -> find();
        $site_mail_smtp_pass = M('setting')-> where(array('name'=>'site_mail_smtp_pass')) -> find();
        $site_mail_smtp_port = M('setting')-> where(array('name'=>'site_mail_smtp_port')) -> find();
        $site_mail_smtp_host = M('setting')-> where(array('name'=>'site_mail_smtp_host')) -> find();
        $dafult_config =  [
            'mail_type' => '1',
            'mail_smtp_host' => $site_mail_smtp_host['value'],//'smtp.163.com',
            'mail_smtp_port' =>  $site_mail_smtp_port['value'],//'465',
            'mail_smtp_user' =>  $site_mail_smtp_user['value'],//'18906912972@163.com',
            'mail_smtp_pass' =>  $site_mail_smtp_pass['value'],//'XMHRBOOIWSKUSAPC',
            'mail_verify_type' => '2',
            'mail_from' =>  $site_mail_smtp_user['value'],//'18906912972@163.com',
        ];
        return $dafult_config;
    }
	
}